package com.xcu.mybatis.sqlsession.proxy;

import com.xcu.mybatis.cfg.Mapper;
import com.xcu.mybatis.utils.Executor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.util.List;
import java.util.Map;

public class Mapperproxy implements InvocationHandler {
    private Map<String, Mapper> mappers;
    private Connection conn;

    //map的Key是全限定类名＋方法名
    public Mapperproxy(Map<String, Mapper> mappers,Connection conn){
        this.mappers = mappers;
        this.conn = conn;
    }
    /**
     * 用于对方法进行增强
     * @param proxy
     * @param method
     * @param args
     * @return
     * @throws Throwable
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //1.获取方法名
        String methodName = method.getName();
        //System.out.println(methodName);
        //2.获取方法所在类的名称
        String className = method.getDeclaringClass().getName();
        //System.out.println(className);
        //3.组合key
        String key = className + "." + methodName;
        //4.获取mappers中的mapper对象
        Mapper mapper = mappers.get(key);
        if (mapper == null){
            throw new IllegalAccessError("传入的参数有误");
        }

        return  new Executor().selectList(mapper,conn);
    }

}
